<?php
/**
 * @abstract 进行H5支付
 * @author ran.ran
 * @example
 * public function actions()
    {
        return [
            'jsapi'=>
            [
                'class'=>'components\JsapipayAction',
                'notifyUrl'=>'http://www.baidu.com'
            ]

        ];
    }
 */

namespace components;

use Opwechat\Phppayment\JsApiPay;
use Opwechat\Phppayment\Lib\WxPayUnifiedOrder;
use Opwechat\Phppayment\Lib\WxPayApi;
use yii\base\Exception;
use Yii;
use yii\web\NotFoundHttpException;
use services\models\wap\WeiXinBindInfo;
use services\models\MemberInfoBestry;

class JsapiPayAction extends BasePayMentAction
{
    public $successUrl = '';
    public $failUrl = '';
    public $mode = 'wxpay';
    
    public function run() {
        try{
            //验证
            $res = $this->validateOrderInfo();

            //用户已经支付及支付金额小于0 。跳转到详情页
            if(!$res['flag']) {
                $url = Yii::$app->urlManager->createUrl(['order-details/listwap']);
                return Yii::$app->response->redirect($url);
            }
             
        } catch(Exception $e){
        
            throw  new NotFoundHttpException();
        }
        
        //获取用户openid
        $tools = new JsApiPay();
         
        //$openId = $tools->GetOpenid();
        //查询member_no
        $data = $res['data'];
        $member_no = MemberInfoBestry::getMemberIdByBestryUid($data->bestry_uid);
        $wx_bind_info =  WeiXinBindInfo::find()->select(['openid'])->where(['member_no'=>$member_no])->one();
        if(empty($wx_bind_info)) {
            throw  new NotFoundHttpException();
        }
        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($this->body);
        $input->SetOut_trade_no($this->payment->order_sn);
        $input->SetTotal_fee($this->payment->order_amount * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 300));
        $input->SetNotify_url($this->returnUrl);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($wx_bind_info->openid);
        $order = WxPayApi::unifiedOrder($input);
        try {
            $jsApiParameters = $tools->GetJsApiParameters($order);
        } catch (Exception $e) {
            throw  new NotFoundHttpException();
        }
       
        return $this->controller->render('wxpay', [
            'jsApiParameters' => $jsApiParameters,
            'success_url' => $this->successUrl.$data->order_info_id,
            'fail_url'=>$this->failUrl,
        ]);

    }
}

?>